#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/11/19 12:05
# @Author : 闫峰
# @File    : mongodb_utils.py
import json
from typing import Union
from datetime import datetime
from urllib import parse

import pymongo
# from dateutil import parser


class MongoDBLink(object):

    # def __init__(self, host,port,username,password,dbname,coll_name):
    #     """
    #
    #     :param host:  Ip
    #     :param port:   端口
    #     :param username:  用户名
    #     :param password:  密码
    #     :param dbname:    数据库名
    #     :param coll_name:  集合名称
    #     """
    #     # 连接mongodb
    #
    #     self.host = host
    #     self.port = port
    #     self.username = username
    #     self.password = password
    #     self.dbname = dbname
    #     self.coll_name = coll_name
    #     # url = "mongodb://{}:{}@{}:{}/?authSource={}".format(self.username,self.password,self.host,self.port,self.dbname)
    #     uri = "mongodb://{}:{}@{}:{}/{}".format(self.username, self.password, self.host, self.port,self.username)
    #     self.client = pymongo.MongoClient(uri)
    #     self.db = self.client[self.dbname]
    #     self.collection  =self.db[self.coll_name]
    #
    #
    #
    # def select(self,sql):
    #     """
    #     查询
    #     :param sql:   mongodb查询语句
    #     :return:
    #     """
    #     res = self.collection.find_one(sql)
    #     return res
    #
    #
    # def select_many(self,sql,field):
    #
    #     result = []
    #     for i in self.collection.find(sql,field):
    #         result.append(i)
    #     return result

    def __init__(self, uri, dbname, coll_name):

        self.dbname = dbname
        self.coll_name = coll_name
        self.uri = uri
        self.client = pymongo.MongoClient(uri)
        # with self.client:
        #     self.db = self.client[self.dbname]
        #     self.collection = self.db[self.coll_name]
        self.db = self.client[self.dbname]
        self.collection = self.db[self.coll_name]
    # def select(self,sql,field):
    #     """
    #     查询
    #     :param sql:   mongodb查询语句
    #     :return:
    #     """
    #     res = self.collection.find(sql,field)
    #     res_dict = []
    #     for one in res:
    #         res_dict.append(one)
    #     return res_dict

    def select(self, sql):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        res = self.collection.find(sql)
        res_dict = []
        for one in res:
            res_dict.append(one)
        return res_dict

    def select_skip_limit(self, sql, page, limit):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        skip = (page -1) * limit
        res = self.collection.find(sql).skip(skip).limit(limit)
        res_dict = []
        for one in res:
            one = self.verify(one)
            res_dict.append(one)
        return res_dict


    def select_skip_limit1(self, sql,asc, skip, limit):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        sort = [(asc, pymongo.ASCENDING)]
        start = (skip - 1) * limit
        res = self.collection.find(sql, sort=sort, limit=limit, skip=start)
        res_dict = []
        for one in res:
            one = self.verify(one)
            res_dict.append(one)
        return res_dict

    def select2(self, sql, field):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        res = self.collection.find(sql, field).skip(0).limit(10)
        res_dict = []
        for one in res:
            res_dict.append(one)

        return res_dict

    def select_sql_pro_sort(self, sql, field, sort,limit):
        res = self.collection.find(sql, field).sort(sort).limit(limit)
        res_dict = []
        for one in res:
            res_dict.append(one)

        return res_dict

    def aggregate(self, pipeline):
        res_dict = []
        ii = self.collection.aggregate(pipeline)
        for i in ii:
            res_dict.append(i)
        return res_dict

    def paginate(self, pipeline, page_num,page_size):
        # 使用 cursor 手动控制查询
        cursor = self.collection.aggregate(pipeline, allowDiskUse=True, cursor={})
        cursor.skip((page_num - 1) * page_size).limit(page_size)
        for doc in cursor:
            print(doc)

    def insert_data(self, data):
        try:
            res = self.collection.insert_one(data)
            return res
        except:
            return
    def verify(self, result: dict) -> Union[dict, None]:
        """验证结果能否被json.dumps序列化"""
        # 尝试变成字符串，解决datetime 无法被json 序列化问题
        try:
            json.dumps(result)
        except TypeError:  # TypeError: Object of type datetime is not JSON serializable
            for k, v in result.items():
                if isinstance(v, datetime):
                    result[k] = str(v)
        return result



if __name__ == '__main__':
    # modb1 = MongoDBLink(
    #     uri='mongodb://reader:33oQm3o6nA9HaLhW#@139.159.193.165:8635,121.37.18.161:8635/?authSource=admin',
    #     dbname='zhcxkj_riskworker', coll_name='Sensitive_AuditV2')
    #
    # pipeline = [
    #     {
    #         "$match": {
    #             "SensitiveType": 1
    #         }
    #     },
    #     {
    #         "$project": {
    #             "SensitiveId": "$SensitiveId",
    #             "SensitiveWord": "$SensitiveWord",
    #             "ProductMaterialSkuNum": "$ProductMaterial.SkuNum",
    #             "ProductMaterialListingNum": "$ProductMaterial.ListingNum"
    #         }
    #     }
    # ]
    #
    # for page in modb1.aggregate(pipeline):  # 每次查询 1000 条数据
    #     for item in page:
    #         print(item)  # 打印当前页查询的结果
    user = parse.quote_plus("viviu")
    passwd = parse.quote_plus("viu@1234")
    sit_charge_mock_data_modb = MongoDBLink(
        uri=f'mongodb://{user}:{passwd}@10.86.3.113:27017/?authSource=admin',
        dbname='sit_charge_mock_data', coll_name='sit_charge_mock_data')
    data = {"request_json.uuid":561119651}
    res_list = sit_charge_mock_data_modb.select(data)
    for res in res_list:
        # print(res)
        print(res.get('request_url'))
        print(res.get('request_json'))
        print(res.get('resp'))